Skip to main content

Overview

The terminal package provides a shared terminal session using PTY (pseudo-terminal) with VT10x emulation. Multiple clients can connect to the same terminal and see synchronized output.

Type

Terminal

Wraps a PTY with VT10x terminal emulation and subscriber management.

Functions

New

Creates a new terminal instance.
int
required
Terminal width in columns (defaults to 80 if < 1)
int
required
Terminal height in rows (defaults to 24 if < 1)
string
required
Working directory for shell (defaults to “/app” if empty)
Example:

Start

Starts the shell process and begins reading output.
Returns: Error if PTY creation or shell start fails Behavior:
  • Creates VT10x terminal emulator
  • Spawns shell process (respects $SHELL env var, defaults to /bin/sh)
  • Sets environment: TERM=xterm-256color
  • Starts background read loop
Example:

Write

Sends input to the terminal (keyboard input, etc.).
[]byte
required
Raw input data to send to PTY
Returns: Bytes written and error Example:

Render

Renders the current terminal state to a string with ANSI codes.
Returns: Rendered terminal output with colors and formatting Features:
  • Caching: Returns cached render if terminal hasn’t changed
  • Colors: Full 256-color ANSI support
  • Cursor: Visual cursor using reverse video effect
  • Optimization: Run-length encoding for color sequences
Example:

Resize

Resizes the terminal dimensions.
int
required
New width in columns
int
required
New height in rows
Behavior:
  • Updates VT10x emulator size
  • Sends SIGWINCH via pty.Setsize()
  • Invalidates render cache

Close

Closes the terminal and cleans up resources.
Cleanup:
  • Closes all subscriber channels
  • Closes PTY file descriptor
  • Kills shell process

Size

Returns current terminal dimensions.

Subscription Pattern

The terminal supports multi-client subscriptions for real-time updates.

Subscribe

Creates a channel for receiving update notifications.
Returns: Channel that receives a signal on each terminal update Example:

Unsubscribe

Removes a subscription channel.
chan struct{}
required
Channel returned by Subscribe()

Implementation Details

Read Loop

The background readLoop() goroutine:
  1. Reads from PTY (4KB buffer)
  2. Writes to VT10x emulator
  3. Marks terminal as dirty
  4. Broadcasts to all subscribers
  5. Exits when shell process terminates

Render Optimization

The terminal caches renders and only re-renders when content changes, reducing CPU usage for idle terminals.

Color Mapping

Maps VT10x colors to ANSI escape codes:
  • Colors 0-7: Standard ANSI (30-37, 40-47)
  • Colors 8-15: Bright ANSI (90-97, 100-107)
  • Colors 16-255: Extended palette (38;5;n, 48;5;n)

Thread Safety

All public methods are thread-safe:
  • mu sync.Mutex protects terminal state
  • subMu sync.RWMutex protects subscriber map